﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.Common.Cache;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using Super.Mvc;
using Super.Common;

namespace Super.Web.Areas.Admin.Controllers
{
    public class StockController : BaseController
    {
        private static SmartCache<string> _stockNoCache = new SmartCache<string>(1);
        public ActionResult Index()
        {
            var adp = new DbContextAdapter();
            var productService = new StockService(adp);
            var page = Query.Params("pageNum");
            var orderField = Query.Post("orderField");
            var orderDirection = Query.Post("orderDirection");


            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var keyword = Query.Post("keyword");
            var Category = Query.Post("Category").ToInt(0);
            var Suppliers = Query.Post("Suppliers").ToInt(0);
            var startTime = Query.Post("startTime").ToDateTime();

            var where = PredicateBuilder.True<Stock>();
            where = where.And(a => a.IsDel == false);

            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(a => a.Product.Title.Contains(keyword.Trim()) ||
                    a.Product.Barcode.Contains(keyword.Trim()) ||
                    a.Product.JianMa.Contains(keyword.Trim())
                    );

                ViewBag.keyword = keyword;
            }

            if (Category > 0)
            {
                where = where.And(a => a.Product.Category_ID == Category);
            }
            if (Suppliers > 0)
            {
                where = where.And(a => a.StockOrder.Supplier_ID == Suppliers);
            }
            if (startTime != null)
            {
                where = where.And(a => a.CreateTime > startTime);
                ViewBag.startTime = startTime;
            }

            var selector = new Func<Stock, dynamic>(a => a.ID);

            ViewBag.orderDirection = "asc";//添加一个默认排序值
            if (!string.IsNullOrEmpty(orderField))
            {
                ViewBag.orderField = orderField;
                ViewBag.orderDirection = orderDirection;
                if (orderField == "cbprice")
                {
                    selector = a => a.Product.CBPrice;
                }

                if (orderField == "lsprice")
                {
                    selector = a => a.Product.LSPrice;
                }
                if (orderField == "createTime")
                {
                    selector = a => a.CreateTime;
                }

            }

            var produtsEnu = productService.Repository.Find(where).OrderByDescending(selector);
            if (orderDirection == "desc")
            {
                produtsEnu = productService.Repository.Find(where).OrderByDescending(selector);
            }
            if (orderDirection == "asc")
            {
                produtsEnu = productService.Repository.Find(where).OrderBy(selector);
            }

            var produts = produtsEnu.Page(page.ToInt(1), PageSize);
            BindPage(produts.ItemCount, page.ToInt(), PageSize);

            ViewBag.Records = produts.ItemCount;

            GetCategory(Category);
            GetSupplier(Suppliers);

            return View(produts.ItemCollection.ToList());
        }

        /// <summary>
        /// 添加和修改库存
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit()
        {
            var pid = Query.Get("pid").ToInt();
            var id = Query.Get("id").ToInt();
            if (id > 0)
            {
                var adp = new DbContextAdapter();
                var productService = new ProductService(adp);
                var productModel = productService.Repository.Find(a => a.ID == id).FirstOrDefault();
                GetSupplier(null);
                return View(productModel);
            }

            else if (pid > 0)
            {
                var adp = new DbContextAdapter();
                var stockService = new StockService(adp);
                var productService = new ProductService(adp);
                var stockModel = stockService.Repository.Find(a => a.ID == pid).FirstOrDefault();
                var productModel = productService.Repository.Find(a => a.ID == stockModel.Product_ID).FirstOrDefault();
                GetSupplier(stockModel.StockOrder.Supplier_ID);
                ViewBag.Count = stockModel.Count;
                ViewBag.StockId = stockModel.ID;
                return View(productModel);

            }
            else
            {
                return ErrorPage();
            }

        }

        [HttpPost]
        public JsonResult Edit(Product model)
        {
            var Supplier_ID = Query.Post("Supplier_ID").ToInt(0);
            var stockId = Query.Post("stockId").ToInt(0);
            var Count = Query.Post("Count").ToInt(0);
            if (Supplier_ID == 0)
            {
                return JsonBack.Tip("请选择供应商！");
            }
            var adp = new DbContextAdapter();
            var stockService = new StockService(adp);

            Stock stockModel = null;//每个产品，可以多个库存
            if (stockId > 0)//编辑库存
            {
                stockModel = stockService.Repository.Find(a => a.ID == stockId).FirstOrDefault();
            }
            if (stockModel == null)
            {
                stockModel = new Stock();
                stockModel.Product_ID = model.ID;
                stockModel.CreateTime = DateTime.Now;
            }
            stockModel.Count = Count;
            stockService.Repository.InsertOrUpdate(stockModel);

            var productService = new ProductService(adp);
            var productModel = productService.Repository.Find(a => a.ID == model.ID).FirstOrDefault();
            if (productModel != null)
            {
                productModel.CBPrice = model.CBPrice;
                productModel.WYLPrice = model.WYLPrice;
                productModel.PFPrice = model.PFPrice;
                productModel.LSPrice = model.LSPrice;
                productService.Repository.InsertOrUpdate(productModel);
            }

            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "stockIndex");
        }


        public ActionResult Input()
        {
            return View();
        }

        public ActionResult InputList()
        {
            var id = Query.Get("id").ToInt(0);
            string stockNo = CacheService.GetStockNo();
            var supplierId = CacheService.GetOneCache("Supplier_ID");
            GetSupplier(supplierId);
            var stockList = CacheService.GetStockList(stockNo);
            ViewBag.stockList = stockList;
            if (id > 0)
            {
                var adp = new DbContextAdapter();
                var productService = new ProductService(adp);
                var productModel = productService.Repository.Find(a => a.ID == id).FirstOrDefault();
                return View(productModel);
            }
            return View();
        }

        [HttpPost]
        public ActionResult AddInputList(Product model)
        {
            var Supplier_ID = Query.Post("Supplier_ID").ToInt(0);
            var Count = Query.Post("Count").ToInt(0);
            if (Supplier_ID == 0)
            {
                return JsonBack.Tip("请选择供应商！");
            }

            CacheService.SetOneCache("Supplier_ID", Supplier_ID);
            var adp = new DbContextAdapter();
            var stockService = new StockService(adp);
            //每个产品，可以多个库存

            var stockNo = CacheService.GetStockNo();

            var stockModel = new Stock();
            stockModel.Product_ID = model.ID;
            stockModel.CreateTime = DateTime.Now;
            stockModel.CBPrice = model.CBPrice;
            stockModel.LSPrice = model.LSPrice;
            stockModel.Count = Count;
            CacheService.AddStockList(stockNo, stockModel);

            return RedirectToAction("InputList");
        }


        public JsonResult SaveInpuList()
        {
            var adp = new DbContextAdapter();
            var stockService = new StockService(adp);
            var stockOrderService = new StockOrderService(adp);
            var stockNo = CacheService.GetStockNo();
            var stockList = CacheService.GetStockList(stockNo);
            if (stockList == null)
            {
                return JsonBack.Tip("请添加入库内容！");

            }
            int supplierId = CacheService.GetOneCache("Supplier_ID");
            var stockOrderModel = new StockOrder();
            stockOrderModel.CreateTime = DateTime.Now;
            stockOrderModel.StockNo = stockNo;
            stockOrderModel.Supplier_ID = supplierId;
            decimal totalMoney = 0;
            foreach (var stock in stockList)
            {
                stock.StockOrder_ID = stockOrderModel.ID;
                stockService.Repository.InsertOrUpdate(stock);
                totalMoney += stock.CBPrice;
            }
            stockOrderModel.TotalMoney = totalMoney;
            stockOrderService.Repository.InsertOrUpdate(stockOrderModel);
            adp.SaveChanges();
            if (adp.ErrorMessage == null)
            {
                CacheService.StockNoCache.ClearCache();
                CacheService.StockCache.ClearCache();
                CacheService.OneCache.Remove("Supplier_ID");
            }

            return JsonBack.Tip(adp.ErrorMessage, "stockInput");
        }

        public ActionResult SubSearch()
        {
            var page = Query.Params("pageNum");
            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var where = PredicateBuilder.True<Stock>();
            where = where.And(a => a.IsDel == false);
            var keyword = Query.Post("keyword");
            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(a => a.Product.Title.Contains(keyword.Trim()) ||
                    a.Product.Barcode.Contains(keyword.Trim()) ||
                    a.Product.JianMa.Contains(keyword.Trim())
                    );

                ViewBag.keyword = keyword;
            }
            var adp = new DbContextAdapter();
            var stockService = new StockService(adp);
            var posService = new PosService(adp);
            var stockList =
                stockService.Repository.Find(where).Page(page.ToInt(1), PageSize);
            BindPage(stockList.ItemCount, page.ToInt(), PageSize);
            ViewBag.Records = stockList.ItemCount;
            ViewBag.Flg = "0";
            if (stockList.ItemCount == 1)
            {
                posService.SetSellItems(UserID, stockList.ItemCollection.FirstOrDefault().ID);
                ViewBag.Flg = "1";
                return View(new List<Stock>());
            }
            return View(stockList.ItemCollection.ToList());
        }

    }
}
